package cn.itsub.sodo.action.interval;

import cn.itsub.sodo.Node;
import cn.itsub.sodo.action.base.FiniteTimeAction;
/**
 * 重复执行一个动作，指定次数
 * @author Mr.Xia@zhenzhigu.com
 * @Date 2016年10月25日
 */
public class Repeat extends IntervalAction {
	
    private int total;	//应该重复的总次数
    private int already;//正在执行第几次
    private FiniteTimeAction action;
    
    public static Repeat create(FiniteTimeAction action,int times){
    	return new Repeat(action, times);
    }
    protected Repeat(FiniteTimeAction action,int times) {
		super(action.getDuration()*times);
		this.action = action;
		this.total = times;
		this.already = 0;
	}
    @Override
    public void start(Node aTarget) {
    	this.already = 0;
    	super.start(aTarget);
    	action.start(aTarget);
    }
    @Override
    public void stop() {
    	action.stop();
    	super.stop();
    }
    @Override
    public void update(float dt) {
    	float t = dt * total;	//已经执行过的次数
    	if(t<=already+1){
    		float r = t % 1.0f;	//r代表一次中的百分比	
    		if(dt==1.0f){
    			r = 1.0f;
    			already++;
    		}
    		action.update(Math.min(r, 1));
    	}else{
    		action.update(1.0f);
    		already++;
    		action.stop();
    		action.start(target);
    		if(already==total){
    			action.update(0);
    		}else{
    			action.update(t-already);
    		}
    	}
    }
    @Override
    public boolean isDone() {
    	return (already==total);
    }
}
